const code = require('../common/code')

module.exports = () => {
    return async (ctx, next) => {
        try {
            const start = new Date().getTime()
            await next()
            const ms = new Date().getTime() - start
            console.log(`Time: ${ms}ms`)
        } catch (err) {
            // ctx.status = err.statusCode || err.status || 500
            switch (err.name) {
                case 'SequelizeValidationError':
                    let message = '参数错误:'
                    err.errors.forEach(item => {
                        message += item.message + ','
                    })
                    ctx.body = code.getCode(code.VALIDATE_ERROR, message)
                    break
                case 'SequelizeUniqueConstraintError':
                    ctx.body = code.getCode(code.VALIDATE_ERROR, '数据已存在')
                    break
                case 'SequelizeForeignKeyConstraintError':
                    ctx.body = code.getCode(code.VALIDATE_ERROR, '有关联数据存在')
                    break
                case 'SequelizeConnectionError':
                    ctx.body = code.getCode(code.SERVER_ERROR, '数据库连接异常, 请重试或联系系统管理员')
                    break
                case 'SequelizeDatabaseError':
                    ctx.body = code.getCode(code.SERVER_ERROR, '数据库连接异常, 请重试或联系系统管理员')
                    break
                default:
                    ctx.status = err.status || 500
                    ctx.body = {
                        code: err.status || 500,
                        type: '请求错误',
                        message: err.message || '服务器出错'
                    }
            }
            console.log(err)
        }
    }
}
